package com.jsz.peini.common.util;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.ResourceBundle;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.jsz.peini.bean.codes.SystemCity;
import com.jsz.peini.bean.codes.SystemCode;
import com.jsz.peini.bean.codes.SystemDistrict;
import com.jsz.peini.bean.codes.SystemDistrictExample;
import com.jsz.peini.bean.codes.SystemSeller;
import com.jsz.peini.bean.codes.SystemSellerExample;
import com.jsz.peini.bean.coupon.CouponInfo;
import com.jsz.peini.bean.coupon.CouponUser;
import com.jsz.peini.bean.order.OrderInfo;
import com.jsz.peini.bean.report.ReportReason;
import com.jsz.peini.bean.search.SearchHot;
import com.jsz.peini.bean.user.UserInfo;
import com.jsz.peini.mapper.codes.SystemDistrictMapper;
import com.jsz.peini.mapper.codes.SystemSellerMapper;
import com.jsz.peini.mapper.report.ReportReasonMapper;
import com.jsz.peini.redis.base.RedisConstants;
import com.jsz.peini.redis.base.RedisUtil;
import com.jsz.peini.redis.base.SerializeUtil;
import com.jsz.peini.redis.util.UserRedisUtil;
import com.jsz.peini.service.codes.ShiedTextService;
import com.jsz.peini.service.codes.SystemCityService;
import com.jsz.peini.service.codes.SystemCodeService;
import com.jsz.peini.service.redDate.RedDateService;
import com.jsz.peini.vo.UserVo;

public class PeiniUtils {
	private static final Logger logger = LoggerFactory.getLogger(PeiniUtils.class);
	public static BlockingQueue<UserInfo> regUserInfos = new LinkedBlockingQueue<UserInfo>();

	public static String HOSTURL;//根目录
	public static String IMGHOST;//图片跟路径
	public static String ANDROIDURL;//安卓下载路径
	public static String IOSURL;//ios下载路径
	
	public static String [] week = {"周一","周二","周三","周四","周五","周六","周日"};
    
	//优惠券领取队列
    public static BlockingQueue<CouponUser> couponUsers = new LinkedBlockingQueue<CouponUser>();
    
    //优惠券使用队列
    public static BlockingQueue<CouponInfo> useCoupons = new LinkedBlockingQueue<CouponInfo>();
    
	//活动报名队列
    /*public static BlockingQueue<ActivityUser> activityUserList = new LinkedBlockingQueue<ActivityUser>();*/
    
	//信用排序队列
    public static BlockingQueue<Integer> creditUpdateList = new LinkedBlockingQueue<Integer>();
    
	//搜索词队列
    public static BlockingQueue<SearchHot> hotSearchList = new LinkedBlockingQueue<SearchHot>();
    public static List<SearchHot> hotList = new ArrayList<SearchHot>();

    //举报原因
	public static HashMap<Integer, List<ReportReason>> reportTypeResns = new HashMap<Integer, List<ReportReason>>();
	
	//城市map  key=code
	public static HashMap<String, SystemCity> cityMap = new HashMap<String, SystemCity>();
	
	//行业map
	public static HashMap<Object, SystemCode> industryMap = new HashMap<Object, SystemCode>();
	
	//业态
	public static LinkedHashMap<Object, SystemSeller> yetaiMap = new LinkedHashMap<Object, SystemSeller>();
	
	//商圈
	public static HashMap<Object, SystemDistrict> distMap = new HashMap<Object, SystemDistrict>();
	
	static{
		try {
			ResourceBundle PropertiesUtil = ResourceBundle.getBundle("config");
			HOSTURL = PropertiesUtil.getString("host");
			IMGHOST = PropertiesUtil.getString("imgHost");
			ANDROIDURL = PropertiesUtil.getString("androidUrl");
			IOSURL = PropertiesUtil.getString("iosUrl");
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
		}
	}
	static{
		try {
			ShiedTextService ShiedTextService = (ShiedTextService)SpringContextUtil.getBean(ShiedTextService.class);
			RedisUtil.delete(RedisConstants.SHIED_TEXT.getBytes());
			List<String> list = ShiedTextService.findShiedTextAll();
			RedisUtil.lpush(RedisConstants.SHIED_TEXT.getBytes(), SerializeUtil.serialize(list));
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
		}
	}
	static{
		try {
			RedDateService redDateService = (RedDateService)SpringContextUtil.getBean(RedDateService.class);
			RedisUtil.delete(RedisConstants.notRedDateList.getBytes());
			List<String> list = redDateService.findShiedTextAll();
			if(list.size()>0)
			{
				for(String str:list)
				{
					RedisUtil.lpush(RedisConstants.notRedDateList.getBytes(),SerializeUtil.serialize(str) );
				}
			}
			
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
		}
	}
	static{
		try {
			ReportReasonMapper reportReasonMapper = (ReportReasonMapper)SpringContextUtil.getBean(ReportReasonMapper.class);
			List<ReportReason> list = reportReasonMapper.selectAll();
			//reportReasonMapper.deleteByPrimaryKey(1);
			
			List<ReportReason> issueType = new ArrayList<ReportReason>();//1问题反馈
			List<ReportReason> userType = new ArrayList<ReportReason>();//2用户举报
			List<ReportReason> sellerType = new ArrayList<ReportReason>();//3举报商家
			List<ReportReason> taskType = new ArrayList<ReportReason>();//4任务举报
			List<ReportReason> imgType = new ArrayList<ReportReason>();//5举报图片
			
			for (ReportReason reportReason : list) {
				switch (reportReason.getTypeid()) {
				case 1:
					issueType.add(reportReason);
					break;
				case 2:
					userType.add(reportReason);
					break;
				case 3:
					sellerType.add(reportReason);
					break;
				case 4:
					taskType.add(reportReason);
					break;
				case 5:
					imgType.add(reportReason);
					break;
				default:
					break;
				}
			}
			
			reportTypeResns.put(1, issueType);
			reportTypeResns.put(2, userType);
			reportTypeResns.put(3, sellerType);
			reportTypeResns.put(4, taskType);
			reportTypeResns.put(5, imgType);
			
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
		}
	}
	
	static{
		try {
			SystemCityService systemCityService = (SystemCityService)SpringContextUtil.getBean(SystemCityService.class);
			List<SystemCity> provinceList = systemCityService.findAllByOrder(1);
			List<SystemCity> cityList = systemCityService.findAllByOrder(2);
			List<SystemCity> countyList = systemCityService.findAllByOrder(3);
			for (SystemCity province : provinceList) {
				cityMap.put(province.getCodesProvince().toString(), province);
				cityMap.put(province.getId().toString(), province);
			}
			for (SystemCity systemCity : cityList) {
				cityMap.put(systemCity.getCodesCity().toString(), systemCity);
				cityMap.put(systemCity.getId().toString(), systemCity);
			}
			for (SystemCity systemCity : countyList) {
				cityMap.put(systemCity.getCodesCounty().toString(), systemCity);
				cityMap.put(systemCity.getId().toString(), systemCity);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
		}
	}
	
	static{
		try {
			SystemCodeService systemCodeService = (SystemCodeService)SpringContextUtil.getBean(SystemCodeService.class);
			List<SystemCode> codeList = systemCodeService.findAll();
			for (SystemCode code : codeList) {
				if(code.getCodes()==106){
					industryMap.put(code.getCodesNum(), code);
				}
			}
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
		}
	}
	
	static{
		try {
			SystemSellerMapper systemSellerMapper = (SystemSellerMapper)SpringContextUtil.getBean(SystemSellerMapper.class);
			SystemSellerExample example = new SystemSellerExample();
			example.setOrderByClause("codes_order asc");
			List<SystemSeller> list = systemSellerMapper.selectByExample(example);
			for (SystemSeller obj : list) {
				if(obj.getCodesSmalltype() == 0){
					yetaiMap.put(obj.getId().toString(), obj);
				}else{
					yetaiMap.put(obj.getId().toString(), obj);
				}
			}
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
		}
	}
	
	static{
		try {
			SystemDistrictMapper systemDistrictMapper = (SystemDistrictMapper)SpringContextUtil.getBean(SystemDistrictMapper.class);
			SystemDistrictExample example = new SystemDistrictExample();			
			List<SystemDistrict> list = systemDistrictMapper.selectByExample(example);
			for (SystemDistrict obj : list) {
				distMap.put(obj.getId(), obj);
				distMap.put(obj.getPlaceCode(), obj);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
		}
	}
	
	/**
	 * token验证
	 * @param userToken
	 * @return userId
	 */
	public static JSONObject validToken(String userToken){
		return UserRedisUtil.validateUserToken(userToken);
	}

	
	/**
	 * 根据Id获取省
	 * @param provinceId
	 * @return
	 */
	public static JSONObject getProviceById(Integer provinceId)
	{
		SystemCity provice = cityMap.get(provinceId.toString());
		JSONObject object = new JSONObject();
		object.put("id", provice.getId());
		object.put("name", provice.getCodesName());
		return object;
	}
	public static String updateNickName(String nickName,String accCode){
		String name=nickName;
		/*if (nickName.matches("^\\d{17}$")) {
			name=accCode;
		}*/
		if(nickName.contains("17")){
			name=accCode;
		}
		return name;
	}
	/**
	 * 获取信用值
	 * @param userInfo
	 * @return
	 */
	public static Integer getCredit(UserInfo userInfo,Integer op){
		int num = 10;
		if(userInfo.getTaskNum() == null){
			userInfo.setTaskNum(0);
		}
		if(userInfo.getSelfNum() == null){
			userInfo.setSelfNum(0);
		}
		if(userInfo.getIdcardNum() == null){
			userInfo.setIdcardNum(0);
		}
		if(userInfo.getTaskNum()>0){
			num += userInfo.getSelfNum()*3/10 + userInfo.getIdcardNum()*2/10 + userInfo.getTaskNum()*4/100;
		}else{//任务如果是负数则不计算
			num += userInfo.getSelfNum()*3/10 + userInfo.getIdcardNum()*2/10;
		}
		
		if(op == 1){
			PeiniUtils.creditUpdateList.add(1);
		}
		
		//更新缓存
		UserVo userVo = UserRedisUtil.getUserVoByUserId(userInfo.getId());
		if(userVo != null){
			userVo.setReputation(new BigDecimal(num));
			UserRedisUtil.addUserToRedis(userVo);
		}
		
		return num;
	}
	
	/**
	 * 是否已经完善信息
	 * @author Han Guohong
	 * @param userInfo
	 * @return
	 */
	public static boolean isAddUserInfo(UserInfo userInfo){
		if(userInfo.getSex() == null || StringUtils.isBlank(userInfo.getBirthday()) || StringUtils.isBlank(userInfo.getNickname()) ){
			return false;
		}
		return true;
	}
	
	/**
	 * 获取星期描述
	 * @author Han Guohong
	 * @param num
	 * @return
	 */
	public static String getWeekDesc(int num){
		num--;
		return week[num];
	}
	
	public static String generateOrderCode(OrderInfo orderInfo){
		String code = "";
		code += orderInfo.getOrderType();
		SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");
		code += sdf.format(new Date());
		String codeStr = String.valueOf(orderInfo.getId());
		if(codeStr.length()> 6){
			codeStr = codeStr.substring(codeStr.length()-6);
		}else if(codeStr.length() < 6){
			for (int i = 0; i < 6-codeStr.length(); i++) {
				code += "0";
			}
		}
		code += codeStr;
		return code;
	}
}
